package com.zzyl.nursing.service.impl;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.*;

import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;

/**
 * 入住Service业务层处理
 *
 * @author yinhui
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /***
     * 入住详情查询
     * @param id：入住信息id
     * @return
     */
//    @Override
//    public CheckInDetailVo detail(Long id) {
//        CheckIn checkIn = checkInMapper.selectById(id);
//        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
//        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
//                .eq(Contract::getElderId, checkIn.getElderId())
//                .eq(Contract::getStatus, 1)
//                //                排序
//                .orderByDesc(Contract::getCreateTime)
//                .last("limit 1"));
//        Elder elder = elderMapper.selectById(checkIn.getElderId());
//
//
//        CheckInDetailVo vo=new CheckInDetailVo();
////        老人信息vo转换
//        CheckInElderVo checkInElderVo = new CheckInElderVo();
//        BeanUtils.copyProperties(elder, checkInElderVo);
//        vo.setCheckInElderVo(checkInElderVo);
////        家属信息转换
//        String remark = checkIn.getRemark();
//        if (!Objects.isNull(remark)) {
//            List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
//        vo.setElderFamilyVoList(elderFamilyVoList);
//        }
//        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
//        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
////        BeanUtils.copyProperties(checkIn, checkInConfigVo);
//        checkInConfigVo.setStartDate(checkIn.getStartDate());
//        checkInConfigVo.setEndDate(checkIn.getEndDate());
//        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
//        vo.setCheckInConfigVo(checkInConfigVo);
////        合同
//        vo.setContract(contract);
//        return vo;
//    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = checkInMapper.selectById(id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, checkIn.getElderId())
                .eq(Contract::getStatus, 1)
                .orderByDesc(Contract::getCreateTime)
                .last("limit 1"));
        Elder elder = elderMapper.selectById(checkIn.getElderId());

        CheckInDetailVo vo = new CheckInDetailVo();

        // 老人信息vo转换
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);

        // 处理性别字段映射问题
        if (elder.getSex() != null) {
            // Elder中 0:女 1:男 -> CheckInElderVo中 0:男 1:女
            checkInElderVo.setSex(elder.getSex() == 0 ? 1 : 0);
        }

        // 处理年龄字段
        if (elder.getBirthday() != null && !elder.getBirthday().isEmpty()) {
            // 计算年龄并设置
            int age = calculateAge(elder.getBirthday());
            checkInElderVo.setAge(age);
        }

        vo.setCheckInElderVo(checkInElderVo);

        // 家属信息转换
        String remark = checkIn.getRemark();
        if (!Objects.isNull(remark) && !remark.isEmpty()) {
            try {
                List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
                vo.setElderFamilyVoList(elderFamilyVoList);
            } catch (Exception e) {
                // JSON解析失败时，设置为空列表或记录日志
                vo.setElderFamilyVoList(new ArrayList<>());
            }
        } else {
            vo.setElderFamilyVoList(new ArrayList<>());
        }

        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        vo.setCheckInConfigVo(checkInConfigVo);

        // 合同
        vo.setContract(contract);
        return vo;
    }

    /**
     * 根据生日计算年龄
     * @param birthday 生日字符串，格式为 yyyy-MM-dd
     * @return 年龄
     */
    private int calculateAge(String birthday) {
        try {
            LocalDate birthDate = LocalDate.parse(birthday);
            LocalDate currentDate = LocalDate.now();
            return Period.between(birthDate, currentDate).getYears();
        } catch (Exception e) {
            return 0;
        }
    }



    @Override
    public void apply(CheckInApplyDto dto) {

//        先检查老人入住了没有，如有记录直接结束
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo()));
        if (elder != null && elder.getStatus().intValue() != 0 && elder.getStatus().intValue() != 5) {
            throw new BaseException("老人已入住");
        }

//        先占床位
        int count = bedMapper.updateBedStatus(dto.getCheckInConfigDto().getBedId());
        if (count == 0) {
            throw new BaseException("床位占用失败");
        }
//        新增、修改老人信息，无老人信息，执行新增，有则修改
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        elder = insertOrUpdate(dto, elder, bed);

//        新增合同签约办理
        insertContract(dto, elder);

//        新增入住信息
        CheckIn checkIn = insertCheckIn(dto, elder, bed);

        //        新增入住配置
        insertCheckInConfig(dto, checkIn);
    }

    private void insertCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(CheckInApplyDto dto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkIn);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(1);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(contract.getStartDate().isAfter(LocalDateTime.now()) ? 1 : 0);
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdate(CheckInApplyDto dto, Elder elder, Bed bed) {
        if (elder != null) {
            fallElder(dto, elder, bed);
//            修改
            elderMapper.updateById(elder);
        } else {
            if (elder == null) {
                elder = new Elder();
                elder.setCreateTime(new Date());
            }
            fallElder(dto, elder, bed);
//            新增
            elderMapper.insert(elder);
        }
        return elder;
    }

    /***
     * 新增老人信息
     * @param dto
     * @param elder
     * @param bed
     */
    private static void fallElder(CheckInApplyDto dto, Elder elder, Bed bed) {
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
    }


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        checkIn.setCreateTime(DateUtils.getNowDate());
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        checkIn.setUpdateTime(DateUtils.getNowDate());
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }


}
